package com.yabiao.idempotent.aop;

import com.yabiao.idempotent.exception.IdempotentException;
import com.yabiao.idempotent.token.TokenService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 *  通过AOP的方式来解析注解
 * </p>
 *
 * @author: zhangyb
 * @create: 2020-09-13
 **/
@Component
//@Aspect
public class IdempotentAspect {

    @Autowired
    private TokenService tokenService;

    @Pointcut("@annotation(com.yabiao.idempotent.annotation.AutoIdempotent)")
    private void pointCut(){

    }

    @Before("pointCut()")
    public void before(JoinPoint joinPoint) throws IdempotentException {
        System.out.println("执行了切面……");
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            tokenService.checkToken(request);
        } catch (IdempotentException e) {
            throw e;
        }
    }

}
